package com.kuanter.kuanterauto.activity;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.method.PasswordTransformationMethod;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.kuanter.kuanterauto.R;
import com.kuanter.kuanterauto.baseui.BaseActivity_NoBar;
import com.kuanter.kuanterauto.baseui.ProApplication;
import com.kuanter.kuanterauto.constants.HttpConfigAPI;
import com.kuanter.kuanterauto.constants.MainConstants;
import com.kuanter.kuanterauto.entity.ActiviteEntity;
import com.kuanter.kuanterauto.main.HomeActivityGroup;
import com.kuanter.kuanterauto.net.HttpTask;
import com.kuanter.kuanterauto.utils.DataLoader;
import com.kuanter.kuanterauto.utils.MD5;
import com.kuanter.kuanterauto.utils.SharePrefenceUtil;
import com.kuanter.kuanterauto.utils.StringUtil;

/** 
 * @author utopia
 * @version 2013-9-22 上午9:22:06
 * 
 */
public class NewActivationNext extends BaseActivity_NoBar {
	TextView top_middle;
	LinearLayout home_chose_City;
	Button left_back;
	
	EditText active_yzm;
	TextView getYZM;
	EditText active_jzm;
	EditText active_next_password;
	TextView button_center;
	LinearLayout lin_yzm;
	
	String hasJYM = "0";
	boolean hasLogin = false;
	String userPassword = "";
	String cardNumber = "";
	String mobileNumber = "";
	
	ImageView iv_hasJZM;
	
	public int TIME = 45;
	DataLoader loader;
	
	String code = "";
	
	ActiviteEntity ae;
	
	Handler mHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			finishProgress();
			if(msg.what == HttpTask.RESULT_OK) {
				String json = (String) msg.obj;
				try {
					if(StringUtil.isSuccess(json)) {
						showToast("激活成功");
						if(ProApplication.getInstance().getCardInfoList() != null) {
							ProApplication.getInstance().getCardInfoList().clear();  //清空卡片信息刷新数据
						}
						Intent intent_main = new Intent(NewActivationNext.this, HomeActivityGroup.class);
						intent_main.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
						startActivity(intent_main);
					} else {
						showToast("激活失败");
					}
				} catch (JSONException e) {
					showToast("网络错误,激活失败");
					e.printStackTrace();
				}
			} else if(msg.what == HttpTask.RESULT_ERROR) {
				showToast("网络错误,获取数据失败");
			}
			super.handleMessage(msg);
		}
		
	};
	
	Handler codeHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			finishProgress();
			String json = (String) msg.obj;
			try {
				if(StringUtil.isSuccess(json)) {
					JSONObject jo = new JSONObject(json);
					code = jo.optString("randomCode");
					
					getYZM.setEnabled(false);
					TIME = 45;
					mHandler.post(new Runnable() {
						@Override
						public void run() {
							if(TIME > 0) {
								getYZM.setText(TIME + "秒后重新收取");
								TIME--;
								mHandler.postDelayed(this, 1000);
							} else {
								getYZM.setEnabled(true);
								getYZM.setText("获取验证码");
								mHandler.removeCallbacks(this);
							}
						}
					});
				} else {
					showToast("获取验证码失败");
				}
			} catch (JSONException e) {
				e.printStackTrace();
			}
			super.handleMessage(msg);
		}
		
	};
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activate_card_new_next);
		Intent intent = getIntent();
		hasJYM = intent.getStringExtra("hasJYM");
		code = intent.getStringExtra("code");
		userPassword = intent.getStringExtra("userPassword");
		cardNumber = intent.getStringExtra("cardNumber");
		mobileNumber = intent.getStringExtra("mobileNumber");
		ae = (ActiviteEntity) intent.getSerializableExtra("ae");
		initTop();
		initUI();
	}
	
	@Override
	protected void onResume() {
		hasLogin = SharePrefenceUtil.checkLogin(NewActivationNext.this);
		if(hasLogin) {
			lin_yzm.setVisibility(View.GONE);
			active_next_password.setVisibility(View.GONE);
			button_center.setText("确认安全码");
		} else {
			lin_yzm.setVisibility(View.VISIBLE);
			active_next_password.setVisibility(View.VISIBLE);
			button_center.setText("确认密码");
		}
		
		if(!hasJYM.equals("0")) {
			iv_hasJZM.setVisibility(View.VISIBLE);
		} else {
			iv_hasJZM.setVisibility(View.GONE);
		}
		super.onResume();
	}



	private void initUI() {
		active_yzm = (EditText) findViewById(R.id.active_yzm);
		getYZM = (TextView) findViewById(R.id.getYZM);
		if(!hasLogin) {
			mHandler.post(new Runnable() {
				@Override
				public void run() {
					if(TIME > 0) {
						getYZM.setText(TIME + "秒后重新收取");
						TIME--;
						mHandler.postDelayed(this, 1000);
					} else {
						getYZM.setEnabled(true);
						getYZM.setText("获取验证码");
						mHandler.removeCallbacks(this);
					}
				}
			});
			getYZM.setText(TIME + "秒后重新收取");
			getYZM.setEnabled(false);
		}
		getYZM.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				showProgress("正在获取验证码...");
				List<NameValuePair> params = new ArrayList<NameValuePair>();
				params.add(new BasicNameValuePair("mobileNumber", mobileNumber));
				params.add(new BasicNameValuePair("userId", ""));
				params.add(new BasicNameValuePair("email", ""));
				new DataLoader(NewActivationNext.this).DisplayData(MainConstants.HOST_test
						+ HttpConfigAPI.RANDOM_CODE, params, codeHandler, "", false);
			}
		});
		
		active_jzm = (EditText) findViewById(R.id.active_jzm);
		if(hasJYM.equals("0")) {
			active_jzm.setVisibility(View.GONE);
		}
		
		active_next_password = (EditText) findViewById(R.id.active_next_password);
		active_next_password.setTransformationMethod(PasswordTransformationMethod.getInstance());
		
		button_center = (TextView) findViewById(R.id.button_center);
		button_center.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				//未登录
				if(!hasLogin) {
					//检测验证码
					if(active_yzm.getText().toString().length() != 6) {
						showToast("请输入6位验证码");
						return;
					} else if(!active_yzm.getText().toString().equals(code)) {
						showToast("验证码不正确");
						return;
					}
					//卡号是否有安全码
					if(!hasJYM.equals("0")) {
						if(active_jzm.getText().toString().length() != 3) {
							showToast("请输入3位安全码");
							return;
						} else if(!active_jzm.getText().toString().equals(hasJYM)) {
							showToast("安全码错误");
							return;
						}
					}
					//检测密码
					String pass = MD5.GetMD5Code(active_next_password.getText().toString());
					if(active_next_password.getText().toString().length() != 6) {
						showToast("请输入6位密码");
					} else if(userPassword != null && !userPassword.equals("") && !pass.equals(userPassword)) {
						showToast("密码不正确");
					} else {
						Intent intent_last = new Intent(NewActivationNext.this, NewActivationLast.class);
						intent_last.putExtra("userPassword", active_next_password.getText().toString());
						intent_last.putExtra("cardNumber", cardNumber);
						intent_last.putExtra("mobileNumber", mobileNumber);
						intent_last.putExtra("ae", ae);
						startActivity(intent_last);
					}
					//已登录
				} else {
					//前一步已经判断是否有安全码，进到这页面表示一定有安全码
					if(active_jzm.getText().toString().length() != 3) {
						showToast("请输入3位安全码");
					} else if(!active_jzm.getText().toString().equals(hasJYM)) {
						showToast("安全码错误");
					} else {
						showProgress("正在激活中...");
						DataLoader loader = new DataLoader(NewActivationNext.this);
						List<NameValuePair> params = new ArrayList<NameValuePair>();
						
						SharedPreferences sp = getSharedPreferences(SharePrefenceUtil.USERINFO, MODE_PRIVATE);
						String phoneNumber = sp.getString("mobileNumber", "");
						NameValuePair nvp_phone = new BasicNameValuePair("mobileNumber",phoneNumber);
						params.add(nvp_phone);
						
						NameValuePair nvp_cardNumber = new BasicNameValuePair("cardNumber",cardNumber);
						params.add(nvp_cardNumber);
						
						loader.DisplayData(HttpConfigAPI.activate_card, params, mHandler, "", false);
					}
				}
			}
		});
		
		lin_yzm = (LinearLayout) findViewById(R.id.lin_yzm);
		
		iv_hasJZM = (ImageView) findViewById(R.id.hasYZM);
	}

	private void initTop() {
		top_middle = (TextView) findViewById(R.id.top_middle);
		top_middle.setText("激活");
		
		home_chose_City = (LinearLayout) findViewById(R.id.home_chose_City);
		home_chose_City.setVisibility(View.GONE);
		
		left_back = (Button) findViewById(R.id.left_back);
		left_back.setText("上一步");
	}
	
	public void exit(View view) {
		finish();
	}
}
